{% extends "members/base.html" %}

{% block title %}个人资料{% endblock %}

{% block content %}
<div class="row">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-person-gear me-2"></i>个人信息</h5>
                <button type="button" class="btn btn-primary btn-sm" id="editProfileBtn">
                    <i class="bi bi-pencil me-1"></i>编辑资料
                </button>
            </div>
            <div class="card-body">
                <form id="profileForm">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="username" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="username" readonly>
                            <div class="form-text text-muted">用户名不可修改</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="email" class="form-label">邮箱地址</label>
                            <input type="email" class="form-control" id="email" readonly>
                            <div id="emailFeedback" class="invalid-feedback"></div>
                            <div class="form-text text-success d-none" id="emailSuccess">
                                <i class="bi bi-check-circle me-1"></i>邮箱可用
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="phone" class="form-label">手机号码</label>
                            <input type="tel" class="form-control" id="phone" readonly>
                            <div id="phoneFeedback" class="invalid-feedback"></div>
                            <div class="form-text text-success d-none" id="phoneSuccess">
                                <i class="bi bi-check-circle me-1"></i>手机号可用
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="realName" class="form-label">真实姓名</label>
                            <input type="text" class="form-control" id="realName" readonly>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="gender" class="form-label">性别</label>
                            <select class="form-select" id="gender" disabled>
                                <option value="">请选择</option>
                                <option value="male">男</option>
                                <option value="female">女</option>
                                <option value="other">其他</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="birthDate" class="form-label">出生日期</label>
                            <input type="date" class="form-control" id="birthDate" readonly>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="profession" class="form-label">职业</label>
                            <input type="text" class="form-control" id="profession" readonly>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="education" class="form-label">学历</label>
                            <select class="form-select" id="education" disabled>
                                <option value="">请选择</option>
                                <option value="highschool">高中及以下</option>
                                <option value="college">大专</option>
                                <option value="bachelor">本科</option>
                                <option value="master">硕士</option>
                                <option value="doctor">博士</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="bio" class="form-label">个人简介</label>
                        <textarea class="form-control" id="bio" rows="3" readonly></textarea>
                    </div>
                    
                    <div class="d-none" id="editActions">
                        <hr>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary" id="saveBtn">
                                <i class="bi bi-check-lg me-1"></i>保存修改
                            </button>
                            <button type="button" class="btn btn-secondary" id="cancelEditBtn">
                                <i class="bi bi-x-lg me-1"></i>取消
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 密码修改 -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-key me-2"></i>修改密码</h5>
            </div>
            <div class="card-body">
                <form id="passwordForm">
                    <div class="mb-3">
                        <label for="currentPassword" class="form-label">当前密码</label>
                        <input type="password" class="form-control" id="currentPassword" required>
                    </div>
                    <div class="mb-3">
                        <label for="newPassword" class="form-label">新密码</label>
                        <input type="password" class="form-control" id="newPassword" required>
                        <div class="form-text">密码长度至少6个字符</div>
                    </div>
                    <div class="mb-3">
                        <label for="confirmNewPassword" class="form-label">确认新密码</label>
                        <input type="password" class="form-control" id="confirmNewPassword" required>
                    </div>
                    <button type="submit" class="btn btn-warning">
                        <i class="bi bi-key me-1"></i>修改密码
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-lg-4">
        <!-- 头像管理 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-person-circle me-2"></i>头像</h5>
            </div>
            <div class="card-body text-center">
                <div class="mb-3">
                    <img src="{{ url_for('static', filename='images/default-avatar-80.svg') }}" 
                         alt="头像" class="rounded-circle" width="120" height="120" id="avatarPreview">
                </div>
                <input type="file" class="d-none" id="avatarInput" accept="image/*">
                <button class="btn btn-outline-primary" onclick="document.getElementById('avatarInput').click()">
                    <i class="bi bi-upload me-1"></i>上传头像
                </button>
                <div class="form-text mt-2">支持 JPG、PNG 格式，文件小于 2MB</div>
                <div id="uploadProgress" class="progress mt-2 d-none">
                    <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                </div>
            </div>
        </div>
        
        <!-- 账户信息 -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-info-circle me-2"></i>账户信息</h5>
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted">注册时间</span>
                    <span id="registrationDate">未知</span>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted">最后登录</span>
                    <span id="lastLogin">未知</span>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted">账户状态</span>
                    <span class="badge" id="accountStatus">正常</span>
                </div>
                <div class="d-flex justify-content-between align-items-center">
                    <span class="text-muted">邮箱验证</span>
                    <span class="badge" id="emailVerification">已验证</span>
                </div>
            </div>
        </div>
        
        <!-- 会员信息 -->
        <div class="card mt-4" id="membershipCard">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-star me-2"></i>会员信息</h5>
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted">会员等级</span>
                    <span class="badge bg-primary" id="membershipLevel">基础会员</span>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted">开始时间</span>
                    <span id="membershipStart">未知</span>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="text-muted">到期时间</span>
                    <span id="membershipEnd">未知</span>
                </div>
                <div class="d-flex justify-content-between align-items-center">
                    <span class="text-muted">状态</span>
                    <span class="badge bg-success" id="membershipStatus">正常</span>
                </div>
                <hr>
                <div class="d-grid">
                    <a href="{{ url_for('members.plans') }}" class="btn btn-outline-primary btn-sm">
                        <i class="bi bi-arrow-up-circle me-1"></i>升级会员
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let isEditing = false;
let originalData = {};
let checkTimeouts = {};

// 页面加载时获取用户信息
document.addEventListener('DOMContentLoaded', function() {
    loadUserProfile();
});

// 加载用户信息
async function loadUserProfile() {
    try {
        const response = await apiRequest('/api/auth/profile');
        if (response.success) {
            updateProfileForm(response.data.user);
            originalData = { ...response.data.user };
        } else {
            showAlert('error', '加载用户信息失败: ' + response.message);
        }
    } catch (error) {
        console.error('加载用户信息失败:', error);
        showAlert('error', '加载用户信息失败，请刷新页面重试');
    }
}

// 更新表单数据
function updateProfileForm(user) {
    // 基本信息
    document.getElementById('username').value = user.username || '';
    document.getElementById('email').value = user.email || '';
    document.getElementById('phone').value = user.phone || '';
    document.getElementById('realName').value = user.real_name || '';
    document.getElementById('gender').value = user.gender || '';
    document.getElementById('birthDate').value = user.birth_date || '';
    document.getElementById('profession').value = user.profession || '';
    document.getElementById('education').value = user.education || '';
    document.getElementById('bio').value = user.bio || '';
    
    // 头像
    if (user.avatar) {
        document.getElementById('avatarPreview').src = user.avatar;
    }
    
    // 账户信息
    if (user.created_at) {
        document.getElementById('registrationDate').textContent = new Date(user.created_at).toLocaleDateString('zh-CN');
    }
    if (user.last_login_at) {
        document.getElementById('lastLogin').textContent = new Date(user.last_login_at).toLocaleString('zh-CN');
    }
    
    const accountStatus = document.getElementById('accountStatus');
    accountStatus.textContent = user.is_active ? '正常' : '禁用';
    accountStatus.className = 'badge ' + (user.is_active ? 'bg-success' : 'bg-danger');
    
    const emailVerification = document.getElementById('emailVerification');
    emailVerification.textContent = user.is_verified ? '已验证' : '未验证';
    emailVerification.className = 'badge ' + (user.is_verified ? 'bg-success' : 'bg-warning');
    
    // 会员信息
    if (user.membership) {
        const membership = user.membership;
        document.getElementById('membershipLevel').textContent = membership.plan_type_display || '基础会员';
        
        if (membership.start_date) {
            document.getElementById('membershipStart').textContent = new Date(membership.start_date).toLocaleDateString('zh-CN');
        }
        if (membership.end_date) {
            document.getElementById('membershipEnd').textContent = new Date(membership.end_date).toLocaleDateString('zh-CN');
        }
        
        const membershipStatus = document.getElementById('membershipStatus');
        membershipStatus.textContent = membership.status === 'active' ? '正常' : '已过期';
        membershipStatus.className = 'badge ' + (membership.status === 'active' ? 'bg-success' : 'bg-secondary');
    }
}

// 编辑资料功能
document.getElementById('editProfileBtn').addEventListener('click', function() {
    toggleEditMode(true);
});

document.getElementById('cancelEditBtn').addEventListener('click', function() {
    toggleEditMode(false);
    updateProfileForm(originalData); // 恢复原始数据
    clearValidationMessages();
});

function toggleEditMode(edit) {
    isEditing = edit;
    const editableFields = ['email', 'phone', 'realName', 'gender', 'birthDate', 'profession', 'education', 'bio'];
    const editBtn = document.getElementById('editProfileBtn');
    const editActions = document.getElementById('editActions');
    
    editableFields.forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field.tagName === 'SELECT') {
            field.disabled = !edit;
        } else {
            field.readOnly = !edit;
        }
        
        // 添加或移除验证事件监听器
        if (edit && (fieldId === 'email' || fieldId === 'phone')) {
            field.addEventListener('input', debounce(() => checkUniqueness(fieldId), 500));
        }
    });
    
    if (edit) {
        editBtn.style.display = 'none';
        editActions.classList.remove('d-none');
    } else {
        editBtn.style.display = 'inline-block';
        editActions.classList.add('d-none');
    }
}

// 实时验证唯一性
async function checkUniqueness(field) {
    const fieldElement = document.getElementById(field);
    const value = fieldElement.value.trim();
    
    if (!value || value === originalData[field]) {
        clearFieldValidation(field);
        return;
    }
    
    try {
        const response = await apiRequest('/api/auth/check-unique', {
            method: 'POST',
            body: JSON.stringify({
                field: field,
                value: value
            })
        });
        
        if (response.success) {
            if (response.data.available) {
                showFieldSuccess(field, field === 'email' ? '邮箱可用' : '手机号可用');
            } else {
                showFieldError(field, field === 'email' ? '邮箱已被使用' : '手机号已被使用');
            }
        }
    } catch (error) {
        console.error('检查唯一性失败:', error);
    }
}

// 显示字段错误
function showFieldError(field, message) {
    const fieldElement = document.getElementById(field);
    const feedbackElement = document.getElementById(field + 'Feedback');
    const successElement = document.getElementById(field + 'Success');
    
    fieldElement.classList.add('is-invalid');
    fieldElement.classList.remove('is-valid');
    
    if (feedbackElement) {
        feedbackElement.textContent = message;
    }
    
    if (successElement) {
        successElement.classList.add('d-none');
    }
}

// 显示字段成功
function showFieldSuccess(field, message) {
    const fieldElement = document.getElementById(field);
    const feedbackElement = document.getElementById(field + 'Feedback');
    const successElement = document.getElementById(field + 'Success');
    
    fieldElement.classList.remove('is-invalid');
    fieldElement.classList.add('is-valid');
    
    if (successElement) {
        successElement.textContent = message;
        successElement.classList.remove('d-none');
    }
}

// 清除字段验证
function clearFieldValidation(field) {
    const fieldElement = document.getElementById(field);
    const successElement = document.getElementById(field + 'Success');
    
    fieldElement.classList.remove('is-invalid', 'is-valid');
    
    if (successElement) {
        successElement.classList.add('d-none');
    }
}

// 清除所有验证消息
function clearValidationMessages() {
    const fields = ['email', 'phone'];
    fields.forEach(clearFieldValidation);
}

// 保存个人资料
document.getElementById('profileForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    if (!isEditing) return;
    
    // 检查是否有验证错误
    const invalidFields = document.querySelectorAll('.is-invalid');
    if (invalidFields.length > 0) {
        showAlert('error', '请修正表单中的错误后再提交');
        return;
    }
    
    const saveBtn = document.getElementById('saveBtn');
    const originalText = saveBtn.innerHTML;
    saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>保存中...';
    saveBtn.disabled = true;
    
    try {
        const formData = {
            email: document.getElementById('email').value.trim(),
            phone: document.getElementById('phone').value.trim() || null,
            real_name: document.getElementById('realName').value.trim(),
            gender: document.getElementById('gender').value,
            birth_date: document.getElementById('birthDate').value,
            profession: document.getElementById('profession').value.trim(),
            education: document.getElementById('education').value,
            bio: document.getElementById('bio').value.trim()
        };
        
        const response = await apiRequest('/api/auth/profile', {
            method: 'PUT',
            body: JSON.stringify(formData)
        });
        
        if (response.success) {
            showAlert('success', '个人资料更新成功');
            originalData = { ...response.data.user };
            toggleEditMode(false);
            clearValidationMessages();
            
            // 更新侧边栏用户信息
            if (window.updateUserInterface) {
                updateUserInterface(response.data.user);
            }
        } else {
            showAlert('error', '更新失败: ' + response.message);
        }
    } catch (error) {
        console.error('更新失败:', error);
        showAlert('error', '更新失败，请稍后重试');
    } finally {
        saveBtn.innerHTML = originalText;
        saveBtn.disabled = false;
    }
});

// 修改密码
document.getElementById('passwordForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const currentPassword = document.getElementById('currentPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmNewPassword = document.getElementById('confirmNewPassword').value;
    
    if (newPassword.length < 6) {
        showAlert('error', '新密码长度至少6个字符');
        return;
    }
    
    if (newPassword !== confirmNewPassword) {
        showAlert('error', '两次输入的新密码不一致');
        return;
    }
    
    try {
        const response = await apiRequest('/api/auth/change-password', {
            method: 'POST',
            body: JSON.stringify({
                current_password: currentPassword,
                new_password: newPassword
            })
        });
        
        if (response.success) {
            showAlert('success', '密码修改成功');
            document.getElementById('passwordForm').reset();
        } else {
            showAlert('error', '修改失败: ' + response.message);
        }
    } catch (error) {
        console.error('修改失败:', error);
        showAlert('error', '修改失败，请稍后重试');
    }
});

// 头像上传
document.getElementById('avatarInput').addEventListener('change', async function(e) {
    const file = e.target.files[0];
    if (!file) return;
    
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
        showAlert('error', '请选择图片文件');
        return;
    }
    
    // 验证文件大小 (2MB)
    if (file.size > 2 * 1024 * 1024) {
        showAlert('error', '图片文件不能超过2MB');
        return;
    }
    
    // 显示进度条
    const progressContainer = document.getElementById('uploadProgress');
    const progressBar = progressContainer.querySelector('.progress-bar');
    progressContainer.classList.remove('d-none');
    progressBar.style.width = '0%';
    
    // 预览图片
    const reader = new FileReader();
    reader.onload = function(e) {
        document.getElementById('avatarPreview').src = e.target.result;
    };
    reader.readAsDataURL(file);
    
    try {
        // 上传图片
        const formData = new FormData();
        formData.append('avatar', file);
        
        // 模拟进度
        progressBar.style.width = '30%';
        
        const response = await fetch('/api/auth/upload-avatar', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('userToken')
            },
            body: formData
        });
        
        progressBar.style.width = '70%';
        
        const data = await response.json();
        
        progressBar.style.width = '100%';
        
        if (data.success) {
            showAlert('success', '头像上传成功');
            
            // 更新侧边栏头像
            const sidebarAvatar = document.getElementById('sidebar-avatar');
            if (sidebarAvatar) {
                sidebarAvatar.src = data.data.avatar_url;
            }
            
            // 更新导航栏头像
            const navAvatar = document.querySelector('.navbar-nav .dropdown-toggle img');
            if (navAvatar) {
                navAvatar.src = data.data.avatar_url;
            }
        } else {
            showAlert('error', '上传失败: ' + data.message);
        }
    } catch (error) {
        console.error('上传失败:', error);
        showAlert('error', '上传失败，请稍后重试');
    } finally {
        // 隐藏进度条
        setTimeout(() => {
            progressContainer.classList.add('d-none');
        }, 1000);
    }
});

// 工具函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function showAlert(type, message) {
    // 移除现有的alert
    const existingAlert = document.querySelector('.alert');
    if (existingAlert) {
        existingAlert.remove();
    }
    
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    document.querySelector('.col-lg-8 .card').insertAdjacentHTML('beforebegin', alertHtml);
    
    // 自动隐藏成功消息
    if (type === 'success') {
        setTimeout(() => {
            const alert = document.querySelector('.alert-success');
            if (alert) {
                alert.remove();
            }
        }, 3000);
    }
}

// API请求函数已在base.html中定义，无需重复定义
</script>
{% endblock %}